package com.aplink.generic.dictionary;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import android.util.SparseArray;

public class GenericDictionary<K, T> extends SparseArray<T> implements
        Serializable {

	private static final long serialVersionUID = -6701388632335830083L;

	public void append(final K key, final T value) {
		super.append(key.hashCode(), value);
	}

	public boolean containsKey(int key) {
		if (this.get(key) != null) {
			return true;
		}
		return false;
	}

	public boolean containsKey(final K key) {
		if (this.get(key.hashCode()) != null) {
			return true;
		}
		return false;
	}

	public void delete(final K key) {
		super.delete(key.hashCode());
	}

	public T get(final K key) {
		return super.get(key.hashCode());
	}

	public T get(final K key, final T valueIfKeyNotFound) {
		return super.get(key.hashCode(), valueIfKeyNotFound);
	}

	public int indexOfKey(final K key) {
		return super.indexOfKey(key.hashCode());
	}

	public boolean isEmpty() {
		return size() == 0;
	}

	public void put(final K key, final T value) {
		super.put(key.hashCode(), value);
	}

	@SuppressWarnings("unchecked")
	private void readObject(ObjectInputStream inputStream) throws IOException,
	        ClassNotFoundException {
		if (inputStream.readLong() == serialVersionUID) {
			int size = inputStream.readInt();
			for (int i = 0; i < size; i++) {
				put(inputStream.readInt(), (T) inputStream.readObject());
			}
		}
	}

	public void remove(final K key) {
		super.remove(key.hashCode());
	}

	public void setValueAt(final K index, final T value) {
		super.setValueAt(index.hashCode(), value);
	}

	private void writeObject(ObjectOutputStream outputStream)
	        throws IOException {
		outputStream.writeLong(serialVersionUID);
		outputStream.writeInt(size());
		for (int i = 0; i < size(); i++) {
			outputStream.writeInt(keyAt(i));
			outputStream.writeObject(valueAt(i));
		}
	}
}
